#include "defs.h"
#include "thread_join_cpp11.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <thread>

CThreadJoinCpp11::CThreadJoinCpp11()
{}

CThreadJoinCpp11::~CThreadJoinCpp11()
{}

void CThreadJoinCpp11::FileThreadFunc()
{
    time_t now = time(NULL);
    struct tm* t = localtime(&now);
    char timeStr[32] = {0};
#ifdef _MSC_VER

    sprintf_s(timeStr, 32, "%04d/%02d/%02d %02d:%02d:%02d",
              t->tm_year + 1900,
              t->tm_mon  + 1,
              t->tm_mday,
              t->tm_hour,
              t->tm_min,
              t->tm_sec);

#else

    snprintf(timeStr, 32, "%04d/%02d/%02d %02d:%02d:%02d",
             t->tm_year + 1900,
             t->tm_mon + 1,
             t->tm_mday,
             t->tm_hour,
             t->tm_min,
             t->tm_sec);

#endif // WIN32

    FILE* fp = fopen(TIME_FILENAME, "w");
    if (fp == NULL) {
        printf("failed to create time.txt\n");
        return;
    }

    size_t sizeToWrite = strlen(timeStr) + 1;
    size_t ret = fwrite(timeStr, 1, sizeToWrite, fp);
    if (ret != sizeToWrite) {
        printf("write file error.\n");
    }

    fclose(fp);
}

int CThreadJoinCpp11::start()
{
    std::thread t(CThreadJoinCpp11::FileThreadFunc);
    if (t.joinable()) {
        t.join();
    }

    FILE* fp = fopen(TIME_FILENAME, "r");
    if (fp == NULL) {
        printf("open file error.\n");
        return -2;
    }

    char buf[32] = {0};
    size_t sizeRead = fread(buf, 1, 32, fp);
    if (sizeRead == 0) {
        printf("read file error.\n");
        fclose(fp);
        return -3;
    }

    printf("cpp11 current time is:%s\n", buf);
    fclose(fp);

    return 0;
}